<template>
    <div>
        我是聊天室
        <ul>
            <li v-for="(item,index) in msgs" :key="index">
                {{item.nickname}}说:{{item.msg}}
            </li>
        </ul>
        昵称:
        <input type="text" name="nickname" v-model="nickname">说:
        <input type="text" name="newMsg" v-model="newMsg">
        <button @click="sendMsg">发送</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            msgs: [],
            newMsg: '',
            nickname: ''
        }
    }, created() {
        //发其请求获取最新的聊天记录数据
        this.$http.get('http://192.168.114.74/msg/getMsg')
            .then(res => {
                //获取数据以后绑定data中的属性，在template中渲染
                this.msgs = res.body.message;
            }, res => {
                console.log('error')
            })
    }, methods: {
        sendMsg() {
            //message:{code:'001',msgs:[{nickname:'xxx',msg:'xxx'}] }
            //发送数据，获取数据
            this.$http.post('http://192.168.114.74/msg/sendMsg', {
                    nickname: this.nickname,
                    msg: this.newMsg
                }, {
                    emulateJSON: true //键值对的形式
                })
                .then(res => {
                    //修改数据模型
                    let result = res.body.message;
                    if (result.code == '001') {
                        return this.msgs = result.msgs;
                    }
                    alert('发送数据失败');
                }, res => {
                    console.log('失败');
                })
        }
    }
}
</script>
<style>
ul li {
    list-style: none;
}
</style>
